<template>
  <div :style="{ ...coreStyle.marginSame(8) }">
    <a-card>
      <a-form ref="sessionsFormQueryRef" :model="sessionsFormQueryModel" labelAlign="left" layout="vertical" :style="{ ...coreStyle.marginBottom(10) }">
        <a-row :gutter="16" v-show="!sessionsFormQueryVisible">
          <a-col :span="8">
            <a-form-item :style="{ ...coreStyle.marginBottom(-8) }">
              <a-input-search v-model:value="sessionsFormQueryModel.keySearchVo" placeholder="关键字搜索" :disabled="sessionsFormQuerySubmitting" @search="sessionsFormQuerySearch" />
            </a-form-item>
          </a-col>
          <a-col :span="16">
            <a-button type="link" :style="{ ...coreStyle.floatRight }" @click="sessionsFormQueryUpDown">
              展开
              <CoreIcon icon="akar-icons:chevron-down" :size="14" />
            </a-button>
          </a-col>
        </a-row>
        <a-row :gutter="16" v-show="sessionsFormQueryVisible">
          <a-col :span="8">
            <a-form-item>
              <a-input-search v-model:value="sessionsFormQueryModel.keySearchVo" placeholder="关键字搜索" :disabled="sessionsFormQuerySubmitting" @search="sessionsFormQuerySearch" />
            </a-form-item>
          </a-col>
          <a-col :span="16">
          </a-col>
          <a-col :span="8">
            <a-form-item label="登录端">
              <a-input v-model:value="sessionsFormQueryModel.loginSideAndLike" placeholder="输入登录端" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="当前时间">
              <a-input-number v-model:value="sessionsFormQueryModel.currentTimes" :style="{ ...coreStyle.width('100%') }" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="账号Id">
              <a-input v-model:value="sessionsFormQueryModel.accountIdAndLike" placeholder="输入账号Id" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="会话信息">
              <a-input v-model:value="sessionsFormQueryModel.sessionsInfoAndLike" placeholder="输入会话信息" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-space :style="{ ...coreStyle.floatRight }">
              <a-button @click="sessionsFormQueryReset">
                <CoreIcon icon="ant-design:clear-outlined" :size="14" />
                重置
              </a-button>
              <a-button type="primary" ghost :loading="sessionsFormQuerySubmitting" @click="sessionsFormQuerySearch">
                <CoreIcon icon="ant-design:search-outlined" :size="14" />
                查询
              </a-button>
              <a-button type="link" @click="sessionsFormQueryUpDown">
                收起
                <CoreIcon icon="akar-icons:chevron-up" :size="14" />
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
      <a-space>
        <!-- <a-button type="primary" ghost @click="sessionsAdd">
          <CoreIcon icon="carbon:add-alt" :size="14" />
          新增
        </a-button> -->
        <!-- <a-button type="dashed" @click="sessionsUpdate" v-if="sessionsListSelectLength === 1">
          <CoreIcon icon="ri:brush-line" :size="14" />
          修改
        </a-button> -->
        <a-popconfirm title="确认下线？" placement="bottom" :disabled="sessionsDeleteDisabled" @confirm="sessionsDelete">
          <a-button type="dashed" :disabled="sessionsDeleteDisabled" danger>
            <CoreIcon icon="la:sign-out-alt" :size="14" />
            下线
          </a-button>
        </a-popconfirm>
        <a-button @click="sessionsDetailInfo" v-if="sessionsListSelectLength === 1">
          <CoreIcon icon="heroicons-outline:light-bulb" :size="14" />
          详情
        </a-button>
      </a-space>
      <a-space :style="{ ...coreStyle.floatRight }">
        <a-button type="link" shape="circle" @click="sessionsListGetDataSet">
          <CoreIcon icon="ci:refresh" :size="22" />
        </a-button>
      </a-space>
      <a-table
        rowKey="id"
        :columns="sessionsListColumns"
        :data-source="sessionsListDataSet"
        :loading="sessionsListLoading"
        :pagination="false"
        bordered
        :customRow="sessionsListCustomRow"
        :row-selection="{ fixed: true, selectedRowKeys: sessionsListSelectedRowKeys, onChange: sessionsListRowOnChange }"
        :scroll="{ x: '100%', y: 550 }"
        :style="{ ...coreStyle.marginTop(10) }"
      >
        <template #loginSideData="{ text }">
          <span>{{ coreToolStore.getDictDisplayName('loginSide', text) }}</span>
        </template>
        <template #currentTimesData="{ text }">
          <span>{{ new Date(text).format() }}</span>
        </template>
      </a-table>
      <a-pagination
        v-model:current="sessionsListDataPage"
        v-model:pageSize="sessionsListDataRows"
        :total="sessionsListDataCount"
        show-size-changer
        show-quick-jumper
        :page-size-options="[ ...coreStyle.antdPaginationPageSizeOptions ]"
        :show-total="(total, range) => coreStyle.antdPaginationShowTotal(total, range)"
        :style="{ ...coreStyle.marginTop(10), ...coreStyle.textAlignCenter }"
        @change="sessionsListPaginationChange"
        @showSizeChange="sessionsListPaginationShowSizeChange"
        v-if="sessionsListPaginationVisible"
      >
      </a-pagination>
      <p :style="{ ...coreStyle.marginTop(14), ...coreStyle.marginBottom(6), ...coreStyle.textAlignCenter }" v-if="!sessionsListPaginationVisible">
        {{ coreStyle.antdPaginationShowTotal(sessionsListDataCount) }}
      </p>
    </a-card>
    <a-drawer
      v-model:visible="sessionsEditDrawerVisible"
      title="编辑会话信息"
      placement="right"
      :closable="false"
      :width="'40%'"
      :header-style="{ ...coreStyle.antdDrawerHeader }"
      :body-style="{ ...coreStyle.margin(50, 0, 30, 0) }"
      @close="sessionsEditDrawerOnClose"
    >
      <a-form ref="sessionsFormRef" :model="sessionsFormModel" :rules="sessionsFormRules" labelAlign="left" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="登录端" name="loginSide">
              <a-input v-model:value="sessionsFormModel.loginSide" placeholder="输入登录端" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="当前时间" name="currentTimes">
              <a-input-number v-model:value="sessionsFormModel.currentTimes" :style="{ ...coreStyle.width('100%') }" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="账号Id" name="accountId">
              <a-input v-model:value="sessionsFormModel.accountId" placeholder="输入账号Id" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="会话信息" name="sessionsInfo">
              <a-input v-model:value="sessionsFormModel.sessionsInfo" placeholder="输入会话信息" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div :style="{ ...coreStyle.antdDrawerFooter }">
        <a-space>
          <a-button @click="sessionsFormReset">
            <CoreIcon icon="ant-design:clear-outlined" :size="14" />
            重置
          </a-button>
          <a-button type="primary" ghost :loading="sessionsFormSaveSubmitting" @click="sessionsFormNextAdd">
            <CoreIcon icon="tabler:player-track-next" :size="14" />
            继续录入
          </a-button>
          <a-button type="primary" ghost :loading="sessionsFormSaveSubmitting" @click="sessionsFormSave">
            <CoreIcon icon="ant-design:save-outlined" :size="14" />
            保存
          </a-button>
        </a-space>
      </div>
    </a-drawer>
    <a-drawer
      v-model:visible="sessionsDetailDrawerVisible"
      title="会话详细信息"
      placement="right"
      :closable="false"
      :width="'40%'"
      :header-style="{ ...coreStyle.antdDrawerHeader }"
      :body-style="{ ...coreStyle.margin(50, 0, 30, 0) }"
    >
      <a-space direction="vertical" :size="20" :style="{ ...coreStyle.width('100%') }">
        <a-descriptions title="基础信息" :column="2" bordered>
          <a-descriptions-item label="登录端" :span="1">{{ coreToolStore.getDictDisplayName('loginSide', sessionsDetailModel.loginSide) }}</a-descriptions-item>
          <a-descriptions-item label="当前时间" :span="1">{{ new Date(sessionsDetailModel.currentTimes).format() }}</a-descriptions-item>
          <a-descriptions-item label="账号" :span="1">{{ sessionsDetailModel.account }}</a-descriptions-item>
          <a-descriptions-item label="账号Id" :span="1">{{ sessionsDetailModel.accountId }}</a-descriptions-item>
          <a-descriptions-item label="会话信息" :span="2">{{ sessionsDetailModel.sessionsInfo }}</a-descriptions-item>
        </a-descriptions>
      </a-space>
      <!-- <div :style="{ ...coreStyle.antdDrawerFooter }">
        <a-space>
          <a-button type="dashed" @click="sessionsDetailUpdate">
            <CoreIcon icon="ri:brush-line" :size="14" />
            修改
          </a-button>
        </a-space>
      </div> -->
    </a-drawer>
  </div>
</template>

<script lang="ts">
import { Options, Vue } from 'vue-class-component'
import { mapStores } from 'pinia'
import { useCoreToolStore } from '/@/store/modules/cn/core/tool/coreToolStore'
import type { Res } from '/@/tool/Res'
import type { Param } from '/@/tool/Param'

import { useSessionsStore } from '/@/store/modules/cn/core/sign/sessionsStore'

import type { Sessions } from '/@/model/cn/core/sign/eo/Sessions'
import { toSessions } from '/@/model/cn/core/sign/eo/Sessions'

import type { SessionsQO } from '/@/model/cn/core/sign/qo/SessionsQO'
import { toSessionsQO } from '/@/model/cn/core/sign/qo/SessionsQO'

import type { SessionsVO } from '/@/model/cn/core/sign/vo/SessionsVO'
import { toSessionsVO } from '/@/model/cn/core/sign/vo/SessionsVO'

@Options({
  name: 'CoreSessions',
  components: {
  },
  computed: {
    ...mapStores(useCoreToolStore, useSessionsStore),
  },
})
export default class CoreSessions extends Vue {

  sessionsListDataSet: Array<SessionsVO> = []

  sessionsListColumns: Array<object> = [
    {
      title: '登录端',
      dataIndex: 'loginSide',
      align: 'center',
      slots: { customRender: 'loginSideData' },
      // ellipsis: true,
      // width: 200,
    },
    {
      title: '当前时间',
      dataIndex: 'currentTimes',
      align: 'center',
      slots: { customRender: 'currentTimesData' },
      // ellipsis: true,
      // width: 200,
    },
    // {
    //   title: '账号Id',
    //   dataIndex: 'accountId',
    //   align: 'center',
    //   // ellipsis: true,
    //   // width: 200,
    // },
    {
      title: '账号',
      dataIndex: 'account',
      align: 'center',
      // ellipsis: true,
      // width: 200,
    },
    // {
    //   title: '会话信息',
    //   dataIndex: 'sessionsInfo',
    //   align: 'center',
    //   // ellipsis: true,
    //   // width: 200,
    // },
  ]

  sessionsListLoading: boolean = false

  sessionsListSelectedRowKeys: string[] = []

  sessionsListSelectData: Array<SessionsVO> = []

  sessionsListSelectLength: number = 0

  sessionsListSelectCurrentRowIndex: number = -1

  sessionsListSelectCurrentRowData: SessionsVO = toSessionsVO()

  sessionsListPaginationVisible: boolean = true

  sessionsListDataPage: number = 1

  sessionsListDataRows: number = 10

  sessionsListDataCount: number = 0

  sessionsListRowOnChange(selectedRowKeys, selectedRows) {
    this.sessionsListSelectedRowKeys = [ ...selectedRowKeys ]
    this.sessionsListSelectData = [ ...selectedRows ]
    this.sessionsListSelectLength = selectedRows.length
  }

  sessionsListCustomRow(record, index) {
    return {
      'class': index === this.sessionsListSelectCurrentRowIndex ? 'ant-table-row-selected' : '',
      onClick: (event) => {
        this.sessionsListSelectCurrentRowIndex = index
        this.sessionsListSelectCurrentRowData = { ...record }
        let selectedRowKeys = [ ...this.sessionsListSelectedRowKeys ]
        let selectedRows = [ ...this.sessionsListSelectData ]
        if (selectedRowKeys.includes(record.id)) {
          this.sessionsListRowOnChange([ ...selectedRowKeys.filter(eo => { return eo !== record.id }) ], [ ...selectedRows.filter(eo => { return eo.id !== record.id }) ])
        } else {
          selectedRowKeys.push(record.id)
          selectedRows.push(record)
          this.sessionsListRowOnChange([ ...new Set(selectedRowKeys) ], [ ...new Set(selectedRows) ])
        }
      },
      onDblclick: (event) => {
        this.sessionsStore.pkVo(this.$toParam<SessionsQO>({ id: this.sessionsListSelectCurrentRowData.id } as SessionsQO)).then((res: Res<SessionsVO>) => {
          if (res.succ) {
            this.sessionsDetailModel = { ...res.data[0] }
            this.sessionsDetailDrawerVisible = true
          } else {
            this.$message.error(res.msg, 6)
          }
        })
      },
    }
  }

  sessionsListGetDataSet() {
    this.sessionsListLoading = true
    this.sessionsListRowOnChange([], [])
    this.sessionsListSelectCurrentRowIndex = -1
    this.sessionsListSelectCurrentRowData = toSessionsVO()
    this.sessionsStore.pagingVo(this.$toParam<SessionsQO>({ currentTimesDesc: 'y' } as SessionsQO, this.sessionsListDataPage, this.sessionsListDataRows)).then((res: Res<SessionsVO>) => {
      if (res.succ) {
        this.sessionsListPaginationVisible = true
        this.sessionsListDataSet = [ ...res.data ]
        this.sessionsListDataCount = res.count
        setTimeout(() => { this.sessionsListLoading = false }, 500)
      } else {
        this.$message.error(res.msg, 6)
        setTimeout(() => { this.sessionsListLoading = false }, 500)
      }
    }).catch(err => {
      setTimeout(() => { this.sessionsListLoading = false }, 500)
    })
  }

  sessionsListPaginationChange() {
    this.sessionsListGetDataSet()
  }

  sessionsListPaginationShowSizeChange() {
    this.sessionsListGetDataSet()
  }

  sessionsFormQueryVisible: boolean = false

  sessionsFormQuerySubmitting: boolean = false

  sessionsFormQueryModel: SessionsQO = toSessionsQO()

  sessionsFormQueryUpDown() {
    this.sessionsFormQueryVisible = !this.sessionsFormQueryVisible
  }

  sessionsFormQueryReset() {
    if (this.$refs.sessionsFormQueryRef) {
      this.$refs.sessionsFormQueryRef.resetFields()
      this.sessionsFormQueryModel = toSessionsQO()
    }
  }

  sessionsFormQuerySearch() {
    this.sessionsFormQuerySubmitting = true
    this.sessionsListLoading = true
    this.sessionsListRowOnChange([], [])
    this.sessionsListSelectCurrentRowIndex = -1
    this.sessionsListSelectCurrentRowData = toSessionsVO()
    this.sessionsStore.queryVo(this.$toParam<SessionsQO>(this.$toSearch({ ...this.sessionsFormQueryModel }))).then((res: Res<SessionsVO>) => {
      if (res.succ) {
        this.sessionsListPaginationVisible = false
        this.sessionsListDataSet = [ ...res.data ]
        this.sessionsListDataCount = res.count
        setTimeout(() => { this.sessionsFormQuerySubmitting = false }, 5000)
        setTimeout(() => { this.sessionsListLoading = false }, 500)
      } else {
        this.$message.error(res.msg, 6)
        setTimeout(() => { this.sessionsFormQuerySubmitting = false }, 5000)
        setTimeout(() => { this.sessionsListLoading = false }, 500)
      }
    }).catch(err => {
      setTimeout(() => { this.sessionsFormQuerySubmitting = false }, 5000)
      setTimeout(() => { this.sessionsListLoading = false }, 500)
    })
  }

  sessionsEditDrawerVisible: boolean = false

  sessionsFormSaveSubmitting: boolean = false

  sessionsFormSaveContinue: boolean = false

  sessionsFormModel: Sessions = toSessions()

  sessionsFormRules: object = {
    // loginSide: [
    //   { type: 'string', required: true, message: '登录端不能为空！', trigger: ['change', 'blur'] },
    // ],
    // currentTimes: [
    //   { type: 'number', required: true, message: '当前时间不能为空！', trigger: ['change', 'blur'] },
    // ],
    // accountId: [
    //   { type: 'string', required: true, message: '账号Id不能为空！', trigger: ['change', 'blur'] },
    // ],
    // sessionsInfo: [
    //   { type: 'string', required: true, message: '会话信息不能为空！', trigger: ['change', 'blur'] },
    // ],
  }

  sessionsFormReset() {
    if (this.$refs.sessionsFormRef) {
      this.$refs.sessionsFormRef.resetFields()
      this.sessionsFormModel = toSessions()
    }
  }

  sessionsFormSubmit() {
    this.sessionsFormSaveSubmitting = true
    this.$refs.sessionsFormRef.validate().then(() => {
      if (this.sessionsFormModel.id) {
        this.sessionsStore.update(this.$toParam<Sessions>(this.sessionsFormModel)).then((res: Res<Sessions>) => {
          if (res.succ) {
            this.$message.success(res.msg, 3)
            this.sessionsFormReset()
            this.sessionsFormSaveSubmitting = false
            if (!this.sessionsFormSaveContinue) {
              this.sessionsEditDrawerVisible = false
              this.sessionsListGetDataSet()
            }
          } else {
            this.$message.error(res.msg, 6)
            setTimeout(() => { this.sessionsFormSaveSubmitting = false }, 3000)
          }
        }).catch(err => {
          setTimeout(() => { this.sessionsFormSaveSubmitting = false }, 3000)
        })
      } else {
        this.sessionsStore.save(this.$toParam<Sessions>(this.sessionsFormModel)).then((res: Res<Sessions>) => {
          if (res.succ) {
            this.$message.success(res.msg, 3)
            this.sessionsFormReset()
            this.sessionsFormSaveSubmitting = false
            if (!this.sessionsFormSaveContinue) {
              this.sessionsEditDrawerVisible = false
              this.sessionsListGetDataSet()
            }
          } else {
            this.$message.error(res.msg, 6)
            setTimeout(() => { this.sessionsFormSaveSubmitting = false }, 3000)
          }
        }).catch(err => {
          setTimeout(() => { this.sessionsFormSaveSubmitting = false }, 3000)
        })
      }
    }).catch(() => {
      setTimeout(() => { this.sessionsFormSaveSubmitting = false }, 3000)
    })
  }

  sessionsFormSave() {
    this.sessionsFormSaveContinue = false
    this.sessionsFormSubmit()
  }

  sessionsFormNextAdd() {
    this.sessionsFormSaveContinue = true
    this.sessionsFormSubmit()
  }

  sessionsAdd() {
    if (this.sessionsFormModel.id) {
      this.sessionsFormReset()
    }
    this.sessionsEditDrawerVisible = true
  }

  sessionsUpdate() {
    this.sessionsStore.pk(this.$toParam<SessionsQO>({ id: this.sessionsListSelectData[0].id } as SessionsQO)).then((res: Res<Sessions>) => {
      if (res.succ) {
        this.sessionsFormReset()
        this.sessionsFormModel = { ...res.data[0] }
        this.sessionsEditDrawerVisible = true
      } else {
        this.$message.error(res.msg, 6)
      }
    })
  }

  sessionsEditDrawerOnClose() {
    if (this.sessionsFormSaveContinue) {
      this.sessionsFormSaveContinue = false
      this.sessionsListGetDataSet()
    }
  }

  sessionsDelete() {
    let param: Array<Sessions> = []
    this.sessionsListSelectData.forEach((eo: SessionsVO) => {
      param.push({ id: eo.id } as Sessions)
    })
    this.sessionsStore.removeBatch(this.$toParam<Sessions>(param)).then((res: Res<Sessions>) => {
      if (res.succ) {
        this.$message.success(res.msg, 3)
        this.sessionsListGetDataSet()
      } else {
        this.$message.error(res.msg, 6)
      }
    })
  }

  get sessionsDeleteDisabled() {
    return this.sessionsListSelectLength > 0 ? false : true
  }

  sessionsDetailDrawerVisible: boolean = false

  sessionsDetailModel: SessionsVO = toSessionsVO()

  sessionsDetailInfo() {
    this.sessionsStore.pkVo(this.$toParam<SessionsQO>({ id: this.sessionsListSelectData[0].id } as SessionsQO)).then((res: Res<SessionsVO>) => {
      if (res.succ) {
        this.sessionsDetailModel = { ...res.data[0] }
        this.sessionsDetailDrawerVisible = true
      } else {
        this.$message.error(res.msg, 6)
      }
    })
  }

  sessionsDetailUpdate() {
    this.sessionsStore.pk(this.$toParam<SessionsQO>({ id: this.sessionsDetailModel.id } as SessionsQO)).then((res: Res<Sessions>) => {
      if (res.succ) {
        this.sessionsFormReset()
        this.sessionsFormModel = { ...res.data[0] }
        this.sessionsDetailDrawerVisible = false
        this.sessionsEditDrawerVisible = true
      } else {
        this.$message.error(res.msg, 6)
      }
    })
  }

  mounted() {
    this.sessionsListGetDataSet()
  }

}
</script>

<style scoped lang="less">

</style>
